//
//  Database.m
//  ITrip
//
//  Created by 1564335 on 15-6-3.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Database.h"

static sqlite3 *dbPoint = nil;

@implementation Database

+ (void)openDataBase
{
    if (dbPoint) {
        return;
    }
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    path = [path stringByAppendingPathComponent:@"ITrip.rdb"];
    sqlite3_open(path.UTF8String, &dbPoint);
    
}

+ (void)createTable
{
    [self openDataBase];
    NSString *sql = @"create table if not exists collect(title NSString, titleId integer, choose integer, imageURL NSString)";
    int result = sqlite3_exec(dbPoint, sql.UTF8String, NULL, NULL, NULL);
    [self judgeResult:result type:@"创建表"];
    
}

+ (void)insertValue:(DbModel *)model
{
    [self openDataBase];
    NSString *sql = [NSString stringWithFormat:@"insert into collect values ('%@', '%ld', '%ld', '%@')", model.title, (long)model.titleId, (long)model.choose, model.imageURL];
    int result = sqlite3_exec(dbPoint, sql.UTF8String, NULL, NULL, NULL);
    [self judgeResult:result type:@"插入"];
}

+ (void)deleteValue:(NSInteger)titleId
{
    [self openDataBase];
    NSString *sql = [NSString stringWithFormat:@"delete from collect where titleId = %ld", (long)titleId];
    int result = sqlite3_exec(dbPoint, sql.UTF8String, NULL, NULL, NULL);
    [self judgeResult:result type:@"删除"];
}

+ (NSArray *)selectData
{
    [self openDataBase];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select * from collect";
    int result = sqlite3_prepare_v2(dbPoint, sql.UTF8String, -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"查询准备成功");
        NSMutableArray *array = [NSMutableArray array];
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *title = sqlite3_column_text(stmt, 0);
            const unsigned char *titleId = sqlite3_column_text(stmt, 1);
            const unsigned char *choose = sqlite3_column_text(stmt, 2);
            const unsigned char *imageURL = sqlite3_column_text(stmt, 3);
            DbModel *model = [DbModel getDbModel];
            model.title = [NSString stringWithUTF8String:(const char *)title];
            model.titleId = [[NSString stringWithUTF8String:(const char *)titleId] integerValue];
            model.choose = [[NSString stringWithUTF8String:(const char *)choose] integerValue];
            model.imageURL = [NSString stringWithUTF8String:(const char *)imageURL];
            [array addObject:model];
        }
        sqlite3_finalize(stmt);
        return array;
    } else {
        NSLog(@"查询准备失败, 原因 : %d", result);
    }
    sqlite3_finalize(stmt);
    return [NSMutableArray array];
}
//判断方法
+ (void)judgeResult:(int)result type:(NSString *)type
{
    if (result == SQLITE_OK) {
        NSLog(@"%@操作成功", type);
    } else {
        NSLog(@"%@操作失败, 原因: %d", type, result);
    }
}
@end
